package br.com.californiahotel.client.viewControler.apartamento;

import java.util.LinkedHashMap;
import java.util.List;

import br.com.californiahotel.client.architecture.viewController.BasicController;
import br.com.californiahotel.client.interfaces.AsyncCallback;
import br.com.californiahotel.client.service.ApartamentoService;
import br.com.californiahotel.client.service.ApartamentoServiceAsync;
import br.com.californiahotel.client.viewControler.apartamento.ApartamentoFormView.Field;
import br.com.californiahotel.shared.models.Apartamento;
import br.com.californiahotel.shared.models.Tipo;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;

public class ApartamentoFormController extends BasicController {

	private final ApartamentoServiceAsync apartamentoService = GWT
			.create(ApartamentoService.class);

	public interface Display extends DisplayController {
		DynamicForm getForm();
	}

	public ApartamentoFormController(Display display) {
		super(display);
		bindType();
	}

	@Override
	protected void bind() {
		getItem(Field.SAVE).addClickHandler(saveButtonClickEvent());
	}

	private void bindType() {
		apartamentoService.findAllTypes(new AsyncCallback<List<Tipo>>() {

			@Override
			public void onSuccess(List<Tipo> result) {
				LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>();
				for (Tipo tipo : result) {
					valueMap.put(tipo.getCdTipo().toString(), tipo.getDescricao());
				}
				getItem(Field.TYPE).setValueMap(valueMap);
				getItem(Field.SAVE).setDisabled(false);
			}
		});
	}

	private ClickHandler saveButtonClickEvent() {
		return new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				apartamentoService.save(
						new Apartamento(Integer
								.parseInt(getItem(Field.NRO_APTO).getValue()
										.toString()), new Tipo(
												(getItem(Field.TYPE).getValue().toString()))),
												new AsyncCallback<Boolean>() {

							@Override
							public void onSuccess(Boolean result) {
								if (result == true) {
									SC.say("Apartamento salvo com sucesso");
								} else {
									SC.say("Falha");
								}
							}
						});
			}

		};
	}

	private Display getDisplay() {
		return ((Display) getDisplayController());
	}

	private FormItem getItem(Field value) {
		return getDisplay().getForm().getItem(value.getFieldName());
	}

}
